package order

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/order/rpc/orderclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateOrderLogic {
	return &UpdateOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateOrderLogic) UpdateOrder(req *types.UpdateOrderReq) (*types.BaseMsgResp, error) {
	// logx.Infof("UpdateProductReq : %+v ", req)

	if len(req.Ids) > 0 {
		res, err := l.svcCtx.OrderRpc.BackendUpdateOrder(l.ctx, &orderclient.BackendUpdateOrderReq{
			TradeState: req.TradeState,
			Ids:        req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}

	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.AdjustAmount == nil || len(strings.TrimSpace(*req.AdjustAmount)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	updatedBy := pointy.GetPointer(jwt.GetBackendUserId(l.ctx))
	res, err := l.svcCtx.OrderRpc.BackendUpdateOrder(l.ctx, &orderclient.BackendUpdateOrderReq{
		Id:           req.Id,
		AdjustAmount: req.AdjustAmount,
		SellerMemo:   req.SellerMemo,
		TradeState:   req.TradeState,
		UpdatedBy:    updatedBy,
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
